package cn.sitemaker.app.fragment;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.networkbench.com.google.gson.Gson;
import com.networkbench.com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import cn.sitemaker.app.R;
import cn.sitemaker.app.api.remote.OSChinaApi;
import cn.sitemaker.app.base.BaseFragment;
import cn.sitemaker.app.bean.AjaxMsg;
import cn.sitemaker.app.bean.PositionEntity;
import cn.sitemaker.app.bean.User;
import cn.sitemaker.app.listener.OnLocationGetListener;
import cn.sitemaker.app.task.LocationTask;
import cn.sitemaker.app.task.RegeocodeTask;
import cn.sitemaker.app.task.RouteTask;
import cn.sitemaker.app.util.UIHelper;
import cz.msebera.android.httpclient.Header;

/**
 * 乘车界面
 *
 * @author kymjs(kymjs123@gmail.com)
 */
public class MapFragment extends BaseFragment implements AMap.OnCameraChangeListener,
        AMap.OnMapLoadedListener, OnLocationGetListener, View.OnClickListener,
        RouteTask.OnRouteCalculateListener {

    private MapView mMapView;

    private AMap mAmap;

    private TextView mAddressTextView;

    private Button mDestinationButton;

    private Marker mPositionMark;

    private LatLng mStartPosition;

    private RegeocodeTask mRegeocodeTask;

    private LinearLayout mDestinationContainer;

    private TextView mRouteCostText;

    private TextView mDesitinationText;

    private LocationTask mLocationTask;

    private ImageView mLocationImage;

    private LinearLayout mFromToContainer;

    private Button mCancelButton;

    private boolean mIsFirst = true;

    private boolean mIsRouteSuccess = false;
    private static ArrayList<Marker> markers=new ArrayList<Marker>();
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup view = (ViewGroup) inflater.inflate(
                R.layout.fragment_map, container, false);
        initView(view, savedInstanceState);
        mLocationTask = LocationTask.getInstance(this.getContext());
        mLocationTask.setOnLocationGetListener(this);
        mRegeocodeTask = new RegeocodeTask(getContext());
        RouteTask.getInstance(getContext())
                .addRouteCalculateListener(this);
        return view;
    }

    public void initView(View view, Bundle savedInstanceState) {
        mAddressTextView = (TextView) view.findViewById(R.id.address_text);
        mDestinationButton = (Button) view.findViewById(R.id.destination_button);
        mDestinationButton.setOnClickListener(this);
        mMapView = (MapView) view.findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        mAmap = mMapView.getMap();
        mAmap.getUiSettings().setZoomControlsEnabled(true);
        mAmap.setOnMapLoadedListener(this);
        mAmap.setOnCameraChangeListener(this);
        mAmap.moveCamera(CameraUpdateFactory.zoomTo(18));

        mDestinationContainer = (LinearLayout) view.findViewById(R.id.destination_container);
        mRouteCostText = (TextView) view.findViewById(R.id.routecost_text);
        mDesitinationText = (TextView) view.findViewById(R.id.destination_text);
        mDesitinationText.setOnClickListener(this);
        mLocationImage = (ImageView) view.findViewById(R.id.location_image);
        mLocationImage.setOnClickListener(this);
        mFromToContainer = (LinearLayout) view.findViewById(R.id.fromto_container);
        mCancelButton = (Button) view.findViewById(R.id.cancel_button);

    }

    private void hideView() {

        mFromToContainer.setVisibility(View.GONE);
        mDestinationButton.setVisibility(View.GONE);
        mCancelButton.setVisibility(View.GONE);
    }

    private void showView() {
        mFromToContainer.setVisibility(View.VISIBLE);
        mDestinationButton.setVisibility(View.VISIBLE);
        if (mIsRouteSuccess) {
            mCancelButton.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onCameraChange(CameraPosition arg0) {
        hideView();
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        showView();
        mStartPosition = cameraPosition.target;
        mRegeocodeTask.setOnLocationGetListener(this);
        mRegeocodeTask .search(mStartPosition.latitude, mStartPosition.longitude);
        // CarUtils.addEmulateData(mAmap, mStartPosition);
        //TODO 后台取得车辆显示在地图上
        OSChinaApi.getUserList(mHandler);
        if (mPositionMark != null) {
            mPositionMark.setToTop();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mLocationTask.onDestroy();
    }

    @Override
    public void onMapLoaded() {

        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.setFlat(true);
        markerOptions.anchor(0.5f, 0.5f);
        markerOptions.position(new LatLng(0, 0));
        markerOptions
                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(getResources(),
                                R.drawable.current_location)));
        mPositionMark = mAmap.addMarker(markerOptions);

        mPositionMark.setPositionByPixels(mMapView.getWidth() / 2,
                mMapView.getHeight() / 2);
        mLocationTask.startSingleLocate();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.destination_button:
                UIHelper.showDisination(getContext());
                break;
            case R.id.location_image:
                mLocationTask.startSingleLocate();
                break;
            case R.id.destination_text:
                UIHelper.showDisination(getContext());
                break;
        }
    }

    @Override
    public void onLocationGet(PositionEntity entity) {
        // todo 这里在网络定位时可以减少一个逆地理编码
        mAddressTextView.setText(entity.address);
        RouteTask.getInstance(getContext()).setStartPoint(entity);

        mStartPosition = new LatLng(entity.latitue, entity.longitude);
        CameraUpdate cameraUpate = CameraUpdateFactory.newLatLngZoom(
                mStartPosition, mAmap.getCameraPosition().zoom);
        mAmap.animateCamera(cameraUpate);

    }

    @Override
    public void onRegecodeGet(PositionEntity entity) {
        mAddressTextView.setText(entity.address);
        entity.latitue = mStartPosition.latitude;
        entity.longitude = mStartPosition.longitude;
        RouteTask.getInstance(getContext()).setStartPoint(entity);
        RouteTask.getInstance(getContext()).search();
    }

    @Override
    public void onRouteCalculate(float cost, float distance, int duration) {
        mDestinationContainer.setVisibility(View.VISIBLE);
        mIsRouteSuccess = true;
        mRouteCostText.setVisibility(View.VISIBLE);
        mDesitinationText.setText(RouteTask
                .getInstance(getContext()).getEndPoint().address);
        mRouteCostText.setText(String.format("预估费用%.2f元，距离%.1fkm,用时%d分", cost,
                distance, duration));
        mDestinationButton.setText("我要用车");
        mCancelButton.setVisibility(View.VISIBLE);
       mDestinationButton.setOnClickListener(null);
    }

    /**
     * 添加车辆
     */
    public static void addCarData(AMap amap, List<User> carList) {
        markers.clear();
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.icon_car);
        for (User user : carList) {
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.setFlat(true);
            markerOptions.anchor(0.5f, 0.5f);
            markerOptions.icon(bitmapDescriptor);
            markerOptions.position(new LatLng(user.getLatitude(), user.getLongtitude()));
            Marker marker = amap.addMarker(markerOptions);
            markers.add(marker);
        }
    }


    private AsyncHttpResponseHandler mHandler =new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
            try {
                Gson gson=new Gson();
                String json = arg2.toString();
                AjaxMsg ajaxMsg=gson.fromJson(json,AjaxMsg.class);
                List<User> list = gson.fromJson(ajaxMsg.getDatas().toString(), new TypeToken<List<User>>(){}.getType());
                //添加车辆
                addCarData(mAmap,list);
                //AppContext.showToastShort(result.getErrorMessage());
            } catch (Exception e) {
                e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
            }
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2,
        Throwable arg3) {}
    };


}
